<!DOCTYPE html>
<html lang="en">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" charset="UTF-8" />
    <title>问卷</title>
    <link rel="stylesheet" type="text/css" href="${request.contextPath}/resources/css/global.css">
    <link rel="stylesheet" type="text/css" href="${request.contextPath}/resources/css/style.css">
</head>

<body>
<div class="questionnaire-h5">
    <div class="qs-box content">
        <!-- 内容 -->
    </div>
    <div style="height:50px;">&nbsp;</div>
</div>
<div style="width: 50%;">
	<a onclick="resetAnswer()" id="btn_reset" class="btn-default btn-save orange-bg" style="width: 50%;">重置</a>
</div>
<div style="width: 50%; float: right;">
	<a onclick="saveAnswer()" id="btn_save" class="btn-default btn-save orange-bg" style="width: 50%;">保存</a>
</div>
</body>
<script src="${request.contextPath}/resources/js/jquery-3.2.1.min.js"></script>
<script src="${request.contextPath}/resources/js/layer/layer.js"></script>
<script type="text/javascript">
	//多个radio 单选效果
	$(function(){
		var loadIndex = layer.load(0, {
	        shade: [0.1,'#fff'] //0.1透明度的白色背景
	    });
		$.when(loadQuestionAjax()).done(function(data){
			layer.closeAll('loading'); //关闭加载层
			if(data.success != true){
        		return false;
        	}
        	//组装html
        	for(var i = 0; i < data.entity.length; i++ ){
        		$(".qs-box").append(loadQuestionHtml(data.entity[i]));
        	}
        	//获取客户填写的答案
        	getAnswer();
        	
        	// 单选效果
        	$(".radio-single").on("click", function(){
    		    $(this).parent().parent().find('.radio-single').removeClass("on");
    		    $(this).parent().parent().find('input.radioclass').removeAttr("checked");
    		    //$(".more-input").hide();
    		    $(this).addClass("on")
    		        .find('input.radioclass').attr("checked", true);
//     		    if( $(this).hasClass("radio-more-input") ) {
//     		        $(".more-input").show();   // 当点击这个radio的时候，出现输入框
//     		    }
    		});
        	// 复选效果
        	$(".radio-multiple").on("click",function(){
        	    if( $(this).hasClass("on") ) {
        	        $(this).removeClass("on")
        	                .find('input.radioclass').removeAttr("checked");
        	    } else {
        	        $(this).addClass("on")
        	                .find('input.radioclass').attr("checked", true);
        	    }
        	});
		});
	});
	//查询数据
	function loadQuestionAjax(){
		var defer = $.Deferred();
		$.ajax({
			type: 'post',
	        url: "${request.contextPath}/appapi/getQuestionList",
	        data:{
	            "questionnaireId": "${questionnaireId}",
	        },
	        dataType: 'json',
	        success: function(data){
	        	defer.resolve(data);
		    }
		});
		return defer.promise();
	}
	//组装html
	function loadQuestionHtml(info){
		var html = '<div class="qs-list font14" level="'+info.level+'" questionId="'+info.id+'" answerType="'+info.answerType+'" isRequired="'+info.isRequired+'">';
		//获取问题题目，并判断时候需要加“必答题”标识
		var question = info.question;
        if(info.isRequired == "1"){
        	question = question + "（必答题）";
        }
        //拼接问题编号及题目
        html+= '<h4 id="h4_'+info.id+'" style="font-size: 18px; font-weight: blod;">'+info.problemCode+' ' + question +'</h4>';
        //获取问题描述，并判段是否需要显示
        var describe = info.questionnaireDescribe;
        if(describe != ""){
        	html += '<p class="qs-note font14 color999">'+describe+'</p>';
        }
        //拼接答案html
        var select_other = ""; //"其他"选项编号
        html += '<div class="flex-list">';
        if(info.answerType == "1"){
        	//当答案为单选框时
        	var json = eval(info.arrayJson);
    	    for(var i = 0; i < json.length; i++){
    	    	if(json[i].answer != "select_other"){
    	    		html += '<label>';
    	    		html += '<span class="radio-default radio-single">';
    	    		html += '<input type="radio" class="radioclass" value="'+json[i].id+'" name="radioAnswer_'+info.id+'">';
    	    		html += '</span>';
    	    		html += '<span class="radio-txt">'+json[i].answer+'</span>';
    	    		html += '</label>';
    	    	}else{
    	    		html += '<label>';
		    		html += '<span class="radio-default radio-single radio-more-input">';
		    		html += '<input type="radio" class="radioclass" value="'+json[i].id+'" name="radioAnswer_'+info.id+'" at="select_other">';
		    		html += '</span>';
		    		html += '<span class="radio-txt">其他</span>';
		    		html += '</label>';
		    		select_other = "T";
    	    	}
    	    }
        }else if(info.answerType == "2"){
        	//当答案为复选框时
        	var json = eval(info.arrayJson);
    	    for(var i = 0; i < json.length; i++){
    	    	if(json[i].answer != "select_other"){
    	    		html += '<label>';
    	    		html += '<span class="radio-default radio-multiple">';
    	    		html += '<input type="checkbox" class="radioclass" value="'+json[i].id+'" name="checkAnswer_'+info.id+'">';
    	    		html += '</span>';
    	    		html += '<span class="radio-txt">'+json[i].answer+'</span>';
    	    		html += '</label>';
    	    	}else{
    	    		html += '<label>';
    	    		html += '<span class="radio-default radio-multiple">';
    	    		html += '<input type="checkbox" class="radioclass" value="'+json[i].id+'" name="checkAnswer_'+info.id+'" at="select_other">';
    	    		html += '</span>';
    	    		html += '<span class="radio-txt">其他</span>';
    	    		html += '</label>';
		    		select_other = "T";
    	    	}
    	    }
        }else if(info.answerType == "3"){
        	html += '<input type="text" class="qs-input" id="input_'+info.id+'" placeholder="请输入相关信息">';
        }
        html += '</div>';
        if(select_other == "T"){
        	html += '<div class="more-input">';
        	html += '<input type="text" class="qs-input" id="input_'+info.id+'" placeholder="请输入相关信息">';
        	html += '</div>';
        }
        html += '</div>';
        return html;
	}
	
	//保存问卷答案
	function saveAnswer(){
		//初始化题目颜色
		initialize();
		var flag = false;
		//定义数组集合，用于往后台传输数据
		var array = new Array();
		//从最顶级回去全部li
		$(".qs-list").each(function() {
			var obj = $(this);
			var html = getQuestion(obj);
			if(!html){
				flag = true;
			}else{
				//将单个问题内容组装成josn,并存入数组
				array.push(html);
			}
		});
		//判断必答题是否全部作答
		if(flag){
			layer.msg("有必答题未填写答案<br />请填写完成后再提交",{
				area: '200px;',
				offset: '50%'
			});
			return false;
		}
		
		//保存开始时隐藏保存按钮
		$("#btn_save").attr("style", "display:none");
		$("#btn_reset").attr("style", "display:none");
		
		var loadIndex = layer.load(0, {
	        shade: [0.1,'#fff'] //0.1透明度的白色背景
	    });
		var host = window.location.host;
		var saveUrl = "http://" + host + "${request.contextPath}/appapi/saveQuestion";
		var params = {};
		params.questionnaireId = "${questionnaireId}";
		params.customerId = "${customerId}";
		params.projectId = "${projectId}";
		params.userId = "${userId}";
		params.json = JSON.stringify(array)
		//保存问题
		$.ajax({
			type: "post",
	        url: "${request.contextPath}/appapi/saveQuestion",
	        data: params,
	        dataType: 'json',
	        success: function(data){
	        	layer.closeAll('loading'); //关闭加载层
	        	if(data.success == true){
	        		layer.msg("保存成功");
	        	}else{
	        		layer.msg("保存失败");
	        		//保存开始时隐藏保存按钮
	        		$("#btn_save").attr("style", "width:50%; display: block;");
	        		$("#btn_reset").attr("style", "width:50%; display:block;");
	        	}
	        }
		});
	}
	//保存问卷时获取问题内容
	function getQuestion(obj){
		var flag = false;
		//获取当前是否必填
		var isRequired = obj.attr("isRequired");
		//获取当前问题的ID
		var questionId = obj.attr("questionId");
		//获取当前问题的类型
		var answerType = obj.attr("answerType");
		//获答案ID、答案文本、"其他答案"ID
		var answerId = "",  answerText = "", select_other = "";
		if(answerType == "1"){
			//获取单选框
			answerId = $('input:radio[name="radioAnswer_'+questionId+'"]:checked').val();
			if(answerId == undefined){
				answerId = "";
			}
			//判断必答题是否选择了答案
			if(isRequired == "1" && answerId == ""){
				$("#h4_"+questionId).attr("style", "color:red");
				flag = true;
			}
			//当选择答案为“其他”时，获取填写的文本答案
			if($('input:radio[name="radioAnswer_'+questionId+'"]:checked').attr("at") == "select_other"){
				select_other = answerId;
				answerText = $("#input_"+questionId).val();
				//判断必答题选择"其他"选项是是否填写了答案
				if(isRequired == "1" && answerText == ""){
					$("#h4_"+questionId).attr("style", "color:red");
					flag = true;
				}
			}
		}else if(answerType == "2"){
			//获取复选框
			$("input[name='checkAnswer_"+questionId+"']").each(function(){
				if($(this).is(':checked')){
			    	answerId += '"' + $(this).attr("value") + '",';	
			    	//当选择答案为“其他”时，获取填写的文本答案
					if($(this).attr("at") == "select_other"){
						select_other = $(this).attr("value");
						answerText = $("#input_"+questionId).val();
						//判断必答题选择"其他"选项是是否填写了答案
						if(isRequired == "1" && answerText == ""){
							$("#h4_"+questionId).attr("style", "color:red");
							flag = true;
						}
					}
			   	}
			});
			//将答案集合组装成数组格式
			if(answerId){
				answerId =  '[' + answerId.substring(0, answerId.length-1) + ']';
			}else if(isRequired == "1"){
				//当答案为空时，判断是否必填
				$("#h4_"+questionId).attr("style", "color:red");
				flag = true;
			}
		}else if(answerType == "3"){
			//获取文本答案
			answerText = $("#input_"+questionId).val();
			//判断必答题是否填写了答案
			if(isRequired == "1" && answerText == ""){
				$("#h4_"+questionId).attr("style", "color:red");
				flag = true;
			}
		}
		//当有必填答案未填时，直接退出方法
		if(flag){
			return false;
		}
	    
	    //组装json
	    var json = {
	    	"questionId": questionId,
	    	"answerType": answerType,
	    	"answerId": answerId,
	    	"select_other": select_other,
	    	"answerText": answerText
	    };
	    return json;
	}
	//初始化题目颜色
	function initialize(){
		$("h4").each(function(){
			$(this).attr("style", "");
		});
	}
	//获取客户填写的答案
	function getAnswer(){
		$.ajax({
			type: "post",
	        url: "${request.contextPath}/appapi/getAnswer",
	        data:{
	        	"questionnaireId": "${questionnaireId}",
	            "customerId": "${customerId}",
	        },
	        dataType: 'json',
	        success: function(data){
	        	if(data.success != true){
	        		return false;
	        	}
	        	setAnswer(data.entity);	
		    }
		});
	}
	//将数据赋值给对应问题
	function setAnswer(data){
		for(var i = 0; i < data.length; i++){
			var info = data[i];
			//问题ID
			var questionId = info.customerProjectQuestionId;
			//选项答案ID
			var answerId = info.customerProjectAnswerId;
			//文本答案（或者“其他”选项文本）
			var answerText = info.answerValue;
			//答案类型
			var answerType = info.answerType;
			if(answerType == "1"){
				$('input:radio[name="radioAnswer_'+questionId+'"]').each(function(){
					if($(this).val() == answerId){
						$(this).attr("checked", true);
						$(this).parent().addClass("on");
					}
				});
			}else if(answerType == "2"){
				$('input[name="checkAnswer_'+questionId+'"]').each(function(){
					if($(this).val() == answerId){
						$(this).attr("checked", true);
						$(this).parent().addClass("on");
					}
				});
			}
			if(answerText != ""){
				$("#input_"+questionId).val(answerText);
			}
		}
	}
	
	function resetAnswer(){
		$(":input").not(":button, :submit, :reset, :hidden").parent().removeClass("on");
		$(":input").not(":button, :submit, :reset, :hidden").val("").prop("checked", false);
	}
</script>
</html>
